package com.eyas.core.jdbc.utils;

import org.springframework.jdbc.core.SqlParameterValue;
import org.springframework.jdbc.core.SqlTypeValue;
import org.springframework.jdbc.core.StatementCreatorUtils;
import org.springframework.lang.Nullable;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;

/**
 * @Auther: 王龙龙
 * @Date: 2019/3/30 10:43
 * @Description:
 */
public abstract class JdbcPrepareParam {


    public static void setStatementParameters(Object[] values, PreparedStatement ps) throws SQLException {
        int[] columnTypes = new int[values.length];
        for(int i=0;i<values.length;i++) {
            if(!(values[i] instanceof SqlParameterValue)) {
                Class clazz = values[i].getClass();
                columnTypes[i] = transformClassTypeToSqlType(clazz);
            }
        }
        setStatementParameters(values,ps,columnTypes);
    }

    /**
     * 将class的类型转换为sqltype
     * @param clazz
     * @return
     */
    private static int transformClassTypeToSqlType(Class clazz) {
        if(clazz==int.class||clazz==Integer.class) {
            return Types.INTEGER;
        }else if(clazz==byte[].class||clazz==Byte[].class) {
            return Types.BINARY;
        }else if(clazz==short.class||clazz==Short.class) {
            return Types.SMALLINT;
        }else if(clazz==long.class||clazz==Long.class) {
            return Types.BIGINT;
        }else if(clazz==float.class||clazz==Float.class) {
            return Types.FLOAT;
        }else if(clazz==double.class||clazz==Double.class) {
            return Types.DOUBLE;
        }else if(clazz==char.class||clazz==Character.class) {
            return Types.CHAR;
        }else if(clazz==boolean.class||clazz==Boolean.class) {
            return Types.BOOLEAN;
        }else {
            //其他类型需要根据注解去解释
            return SqlTypeValue.TYPE_UNKNOWN;
        }
    }


    /**
     * jdbc 对ps赋值
     * @param values
     * @param ps
     * @param columnTypes
     * @throws SQLException
     */
    public static void setStatementParameters(Object[] values, PreparedStatement ps, @Nullable int[] columnTypes)
            throws SQLException {

        int colIndex = 0;
        for (Object value : values) {
            colIndex++;
            if (value instanceof SqlParameterValue) {
                SqlParameterValue paramValue = (SqlParameterValue) value;
                StatementCreatorUtils.setParameterValue(ps, colIndex, paramValue, paramValue.getValue());
            }
            else {
                int colType;
                if (columnTypes == null || columnTypes.length < colIndex) {
                    colType = SqlTypeValue.TYPE_UNKNOWN;
                }
                else {
                    colType = columnTypes[colIndex - 1];
                }
                StatementCreatorUtils.setParameterValue(ps, colIndex, colType, value);
            }
        }
    }
}
